package com.ebc.eservice.config.filter;

import com.alibaba.fastjson.JSON;
import com.ebc.eservice.pojo.UserDT;
import com.ebc.eservice.util.JsonResult;
import com.ebc.eservice.util.JwtUtil;
import com.ebc.eservice.util.WebUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

@Component
@Slf4j
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader("Authorization");
        if (!StringUtils.hasText(token)) {
            log.info("{}", "无token,请登录。");
            //放行
            filterChain.doFilter(request, response);
            return;
        }
        //解析token
        String userId=null;
        try {
            Claims claims = JwtUtil.parseJWT(token);
            System.out.println(claims);
            userId = claims.getSubject();
        } catch (Exception e) {
            e.printStackTrace();
            log.info("{}", "token非法");
            JsonResult result = new JsonResult(401,"token已失效,请重新登录",null);
            String json = JSON.toJSONString(result);
            //处理异常
            WebUtils.renderString(response,json);
            throw new RuntimeException("token非法");
    };
        //从redis中获取用户信息
        String redisKey = "tk" + userId;
        UserDT user = (UserDT) redisTemplate.opsForValue().get(redisKey);

        if(Objects.isNull(user)){
            System.out.println("登录超时，token过期");
            JsonResult result = new JsonResult(401,"登录超时,请重新登录",null);
            String json = JSON.toJSONString(result);
            //处理异常
            WebUtils.renderString(response,json);
        }
        try {
            UsernamePasswordAuthenticationToken authenticationToken =
                    new UsernamePasswordAuthenticationToken(user.getUser(),null,user.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("token失效,登录超时");
        }
        //放行
        filterChain.doFilter(request, response);
    }
}
